package club.xiaojiawei.binarytree;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 5/20/22 1:14 AM
 * @question 108. 将有序数组转换为二叉搜索树
 * @description 给你一个整数数组 nums ，其中元素已经按 升序 排列，请你将其转换为一棵 高度平衡 二叉搜索树。
 * 高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。
 */
public class SortedArrayToBST108 {

    public static void main(String[] args) {
        SortedArrayToBST108 test = new SortedArrayToBST108();
        TreeNode result = test.sortedArrayToBST(new int[]{0, 1, 2, 3, 4, 5});
        System.out.println(result);
    }

    /**
     * 递归+中序遍历
     * @param nums
     * @return
     */
    public TreeNode sortedArrayToBST(int[] nums) {
        return build(nums, 0 , nums.length - 1);
    }

    public TreeNode build(int[] nums, int left, int right){
        int middle = (right + left + 1) >> 1;
        TreeNode root = new TreeNode(nums[middle]);
        if (right - left > 4){
            root.left = build(nums, left, middle - 1);
            root.right = build(nums, middle + 1, right);
        }else {
            TreeNode temp = root;
            for (int i = middle - 1; i >= left; i--){
                temp.left = new TreeNode(nums[i]);
                temp = temp.left;
            }
            temp = root;
            for (int i = middle + 1; i <= right; i++){
                temp.right = new TreeNode(nums[i]);
                temp = temp.right;
            }
        }
        return root;
    }

    /**
     * 官方-递归+中序遍历
     * @param nums
     * @return
     */
    public TreeNode sortedArrayToBST2(int[] nums) {
        return helper(nums, 0, nums.length - 1);
    }

    public TreeNode helper(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        // 总是选择中间位置左边的数字作为根节点
        int mid = (left + right) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, left, mid - 1);
        root.right = helper(nums, mid + 1, right);
        return root;
    }

    static class TreeNode{

        private int val;

        private TreeNode left;

        private TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public TreeNode getLeft() {
            return left;
        }

        public void setLeft(TreeNode left) {
            this.left = left;
        }

        public TreeNode getRight() {
            return right;
        }

        public void setRight(TreeNode right) {
            this.right = right;
        }
    }
}
